package com.kgis.fm.business.jsinterface
{
	import com.kgis.fm.business.component.infoWindow.InfoWindow;
	import com.kgis.fm.business.effects.ExtendPolylineEffect;
	import com.kgis.map.Map;
	import com.kgis.map.common.enum.LayerTypeEnum;
	import com.kgis.map.common.util.GlowTween;
	import com.kgis.map.feature.Feature;
	import com.kgis.map.geometry.ArrowLineGeometry;
	import com.kgis.map.geometry.PointGeometry;
	import com.kgis.map.geometry.PolygonGeometry;
	import com.kgis.map.geometry.PolylineGeometry;
	import com.kgis.map.geometry.basetype.Location;
	import com.kgis.map.layer.FeatureLayer;
	import com.kgis.map.style.PointStyle;
	import com.kgis.map.style.PolygonStyle;
	import com.kgis.map.style.PolylineStyle;
	
	import flash.events.MouseEvent;
	import flash.external.ExternalInterface;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.core.UIComponent;
	import mx.managers.PopUpManager;

	public class JSExternalInterface
	{
		private var _map:Map;

		public function JSExternalInterface(map:com.kgis.map.Map)
		{
			_map=map;

			ExposeExternalInterface();
		}

		private function ExposeExternalInterface():void
		{
			//窗口居中
			ExternalInterface.addCallback("centerAt", this.centerAt);
			ExternalInterface.addCallback("zoomAt", this.zoomAt);

			ExternalInterface.addCallback("panUp", this.panUp);

			ExternalInterface.addCallback("clearAllGraphics", this.clearAllGraphics);

			ExternalInterface.addCallback("clearGraphicsLayer", this.clearGraphicsLayer);
			ExternalInterface.addCallback("removeFeatureInLayer", this.removeFeatureInLayer);
	
			ExternalInterface.addCallback("addPointInfoWindow", this.addPointInfoWindow);

			ExternalInterface.addCallback("animateArrowLineInTime", this.animateArrowLineInTime);

			ExternalInterface.addCallback("animateArrowLineInSpeed", this.animateArrowLineInSpeed);

			ExternalInterface.addCallback("flashPoints", this.flashPoints);

			ExternalInterface.addCallback("flashPolyline", this.flashPolyline);

			ExternalInterface.addCallback("flashPolygon", this.flashPolygon);

			ExternalInterface.addCallback("onMousewheelHandler", this.onMousewheelHandler);
			/**
			 *绘制图形统一接口
			 * @param id	图形Id
			 * @param geometryObject 图形几何Json对象,格式参考Arcgis server Rest API之GeometryObject
			 * @param tipMode	tip显示模式，可为none\open\hover\click,默认为none
			 * @param attribute 属性Json对象,默认为空
			 * @param symbolObject	图形样式Json对象,默认为空,格式参考Arcgis server Rest API之Symbol Objects
			 * @param tipClass	tip类型,可为空,默认为"SimpleHtml"
			 * @param tipWidth	tip框宽度,默认为200，可为空
			 * @param tipHeight	tip框高度,默认为200，可为空
			 * @param tipUrl	当tipClass为IFrame时，IFrame地址,可为空
			 * @param autoZoom 是否自动缩放,可为空，默认值为true
			 * @param layerId 在指定层上添加标记
			 *
			 */
			//function addGraphic(id,geometryObject,tipMode,attribute,symbolObject,tipClass,tipWidth,tipHeight,tipUrl,autoZoom,layerId)
			ExternalInterface.addCallback("addGraphic", this.addGraphic);

		}


		/**
		 * 按时间动画箭头线
		 *
		 * @param polylineString 线字符串
		 * @param arrowLineSymbolObject 脚本传入的箭头线符号对象
		 * @param duration 持续时间（毫秒）
		 */
		public function animateArrowLineInTime(polylineString:String, arrowLineSymbolObject:Object, duration:Number, layerId:int):void
		{
//			Alert.show("polylineString:" + polylineString);
			try
			{
				var dynamicLayer:FeatureLayer=_map.getLayerById(layerId) as FeatureLayer;
				if (null == dynamicLayer){
					dynamicLayer=new FeatureLayer(layerId, "红线图层-线");
					dynamicLayer.layerType=LayerTypeEnum.DYNAMICLAYER;
					_map.addLayer(dynamicLayer);
				}
				var linestyle:PolylineStyle=new PolylineStyle();
				linestyle.color=arrowLineSymbolObject.color;
				linestyle.alpha=arrowLineSymbolObject.alpha;
				var width:Array=[1];
				width.push(Number(arrowLineSymbolObject.width));
				linestyle.width=width;
				if (arrowLineSymbolObject.style)
				{
					if (arrowLineSymbolObject.style != "solid")
						linestyle.dashMode=arrowLineSymbolObject.style;
				}
				dynamicLayer.geoStyle=linestyle;
				var coords:Array=polylineString.split(",");
				var pointList:ArrayCollection=new ArrayCollection();
				for (var i:int=0; i < coords.length; i+=2)
				{
					pointList.addItem(new PointGeometry(coords[i], coords[i + 1], 0));
				}
				var newLine:ArrowLineGeometry=new ArrowLineGeometry();
				newLine.pointList=pointList;
				newLine.duration=duration;
				var feature:Feature=new Feature();
				feature.geometry=newLine;
				var effect:ExtendPolylineEffect=new ExtendPolylineEffect(feature);
				effect.duration=duration;
				//(feature as UIComponent).setStyle("addedEffect", effect);
				dynamicLayer.addFeature(feature);
				feature.executeDrawing();
				effect.play();
				_map.center=feature.getLocation();
			}catch (error:Error)
				{
					Alert.show("参数错误" + error.message);
				}
		}

		/**
		 * 按速度动画箭头线
		 *
		 * @param polylineString 线字符串
		 * @param arrowLineSymbolObject 脚本传入的箭头线符号对象
		 * @param speed 时速（每小时移动多少地图长度）
		 * @param ratio 真实动画比。实际1小时相当于多少毫秒动画时间
		 */
		public function animateArrowLineInSpeed(polylineString:String, arrowLineSymbolObject:Object, speed:Number, ratio:Number):void
		{
			try
			{
				var dynamicLayer:FeatureLayer=_map.getLayerById(-1000) as FeatureLayer;
				if (!dynamicLayer)
					dynamicLayer=new FeatureLayer(-1000, "红线图层-线");
				dynamicLayer.layerType=LayerTypeEnum.DYNAMICLAYER;
				var linestyle:PolylineStyle=new PolylineStyle();
				linestyle.color=arrowLineSymbolObject.color;
				linestyle.alpha=arrowLineSymbolObject.alpha;
				linestyle.width=arrowLineSymbolObject.width;
				if (arrowLineSymbolObject.style)
				{
					if (arrowLineSymbolObject.style != "solid")
						linestyle.dashMode=arrowLineSymbolObject.style;
				}
				dynamicLayer.geoStyle=linestyle;
				_map.addLayer(dynamicLayer);
				var coords:Array=polylineString.split(",");
				var pointList:ArrayCollection=new ArrayCollection();
				for (var i:int=0; i < coords.length; i+=2)
				{
					pointList.addItem(new PointGeometry(coords[i], coords[i + 1], 0));
				}

				var newLine:ArrowLineGeometry=new ArrowLineGeometry();
				newLine.pointList=pointList;
				var feature:Feature=new Feature();
				feature.geometry=newLine;
				var duration:Number=length / speed * ratio;
				var effect:ExtendPolylineEffect=new ExtendPolylineEffect(feature);
				effect.duration=duration;

				dynamicLayer.addFeature(feature);
				feature.executeDrawing();
				effect.play();

				_map.center=feature.getLocation();

			}
			catch (error:Error)
			{
				Alert.show("参数错误");
			}
		}

		/**
		 * 计算平面长度
		 *
		 * @param pointArray 点集
		 *
		 * @return 点集连成线的平面长度
		 */
		private function getLength(pointArray:ArrayCollection):Number
		{
			if (pointArray.length < 2)
			{
				throw new ArgumentError("点集至少应包含2个点");
			}

			var length:Number=0.0;
			// 遍历 n-1 个点
			for (var i:int=0; i < pointArray.length - 1; i++)
			{
				var pt1:PointGeometry=PointGeometry(pointArray[i]);
				var pt2:PointGeometry=PointGeometry(pointArray[i + 1]);

				length+=Math.sqrt((pt1.x - pt2.x) * (pt1.x - pt2.x) + (pt1.y - pt2.y) * (pt1.y - pt2.y));
			}

			return length;
		}

		//todo
		public function addGraphic(id:String, geometryObject:Object, tipMode:String="none", attribute:Object=null, symbolObject:Object=null, tipClass:String="", tipWidth:Number=200, tipHeight:Number=200, tipUrl:String="", autoZoom:Boolean=true, layerId:String="HightlightLayer"):void
		{

		}

		/**
		 * 地图居中
		 *
		 * @param X 地图中点 X 坐标
		 * @param Y 地图中点 Y 坐标
		 */
		public function centerAt(x:Number, y:Number):void
		{
			_map.center=new Location(x, y);
		}

		public function zoomAt(level:int, x:Number, y:Number):void
		{
			_map.center=new Location(x, y);
			_map.zoom=level;
		}

		public function clearGraphicsLayer(layerId:int):void
		{
			_map.clearLayerByLayerId(layerId);
		}
		public function removeFeatureInLayer(layerId:int,featureId:int):void{
			_map.removeFeatureInLayer(layerId,featureId);
		}
		public function clearAllGraphics():void
		{
			_map.removeAllDynamicLayer();
		}

		/**
		 * 地图向上平移
		 */
		public function panUp():void
		{
			_map.center=new Location(_map.center.x, _map.extent.height / 4 + _map.center.y);
		}

		/**
		 * 地图向下平移
		 */
		public function panDown():void
		{
			_map.center=new Location(_map.center.x, _map.center.y - _map.extent.height / 4);
		}

		/**
		 * 地图向左平移
		 */
		public function panLeft():void
		{
			_map.center=new Location(_map.center.x - _map.extent.width / 4, _map.center.y);
		}

		/**
		 * 地图向右平移
		 */
		public function panRight():void
		{
			_map.center=new Location(_map.center.x + _map.extent.width / 4, _map.center.y);
		}

		/**
		 * 刷新图层
		 *
		 * @param layerId 图层id
		 */
		public function refreshFeatureLayerByID(layerId:Number):void
		{
			_map.refreshFeatureLayerByID(layerId);
		}

		/**
		 * @param id  设施的id
		 * @param x   坐标x
		 * @param y   坐标y
		 * @param markerSymbolObject markerSymbolObject.symbolName
		 * @param mode 1：外面图片  2：符号库中的符号
		 * @param title
		 * @param simpleHtml
		 * @param tipwidth
		 * @param tipheight
		 * @param xoff
		 * @param yoff
		 * @param layerId 在指定层上添加标记
		 *
		 * */
		public function addPointInfoWindow(id:String, x:Number, y:Number, markerSymbolObject:Object=null, mode:String="click", title:String="", simpleHtml:String="", tipwidth:Number=300, tipheight:Number=200, xoff:Number=0, yoff:Number=0, layerId:int=-100):void
		{
			//先加point，其中point的符号是markerSymbolObject，然后给这个符号增加click事件，点击弹出对话框显示内容为simpleHtml
			try
			{
				var dynamicLayer:FeatureLayer=_map.getLayerById(layerId) as FeatureLayer;
				if (null == dynamicLayer)
				{
					dynamicLayer=new FeatureLayer(layerId, "红线图层-点");
					dynamicLayer.layerType=LayerTypeEnum.DYNAMICLAYER;
					_map.addLayer(dynamicLayer);
				}
				var pointstyle:PointStyle=new PointStyle();
				//1 用符号库里面的符号  2 代表图片
				if (markerSymbolObject.hasOwnProperty("displayMode"))
				{
					pointstyle.displayMode=markerSymbolObject.displayMode;
				}
				if (markerSymbolObject.hasOwnProperty("symbolName"))
				{
					pointstyle.symbolName=markerSymbolObject.symbolName;
				}
				if (markerSymbolObject.hasOwnProperty("scale"))
				{
					pointstyle.scale=markerSymbolObject.scale;
				}
				if (markerSymbolObject.hasOwnProperty("color"))
				{
					pointstyle.color=markerSymbolObject.color;
				}
				if (markerSymbolObject.hasOwnProperty("alpha"))
				{
					pointstyle.alpha=markerSymbolObject.alpha;
				}
				if (markerSymbolObject.hasOwnProperty("angle"))
				{
					pointstyle.rotation=markerSymbolObject.angle;
				}
				var feature:Feature;
				feature=dynamicLayer.getFeatureById(Number(id));
				if (null == feature)
				{
					feature=new Feature();
					feature.objectId=Number(id);
					dynamicLayer.addFeature(feature);
					var newPoint:PointGeometry=new PointGeometry(x, y, 0);
					feature.geometry=newPoint;
				}
				else
				{
					PointGeometry(feature.geometry).x=x;
					PointGeometry(feature.geometry).y=y;
				}
				var attributes:Object=new Object();
				attributes.title=title;
				attributes.height=tipheight;
				attributes.width=tipwidth;
				attributes.simpleHtml=simpleHtml;
				feature.geoStyle=pointstyle;
				feature.attributes=attributes;
				feature.executeDrawing();
			}
			catch (error:Error)
			{
				Alert.show("参数错误" + error.message);
			}
		}

		/**
		 * 闪烁点
		 *
		 * @param pointsString 点字符串
		 * @param delay 闪烁间隔（毫秒）
		 * @param repeatCount 闪烁次数
		 * @param markerSymbolObject 脚本传入的标记符号对象
		 */
		public function flashPoints(pointsString:String, delay:Number, repeatCount:int, markerSymbolObject:Object):void
		{

			try
			{
				var dynamicLayer:FeatureLayer=_map.getLayerById(-100) as FeatureLayer;
				if (!dynamicLayer)
					dynamicLayer=new FeatureLayer(-100, "红线图层-点");

				dynamicLayer.layerType=LayerTypeEnum.DYNAMICLAYER;
				var pointstyle:PointStyle=new PointStyle();

				pointstyle.displayMode=markerSymbolObject.displayMode;
				pointstyle.symbolName=markerSymbolObject.symbolName;
				pointstyle.scale=markerSymbolObject.scale;
				pointstyle.color=markerSymbolObject.color;
				pointstyle.alpha=markerSymbolObject.alpha;
				pointstyle.rotation=markerSymbolObject.angle;

				dynamicLayer.geoStyle=pointstyle;
				_map.addLayer(dynamicLayer);
				var coords:Array=pointsString.split(";");
				for (var i:int=0; i < coords.length; i++)
				{
					var coord:Array=coords[i].split(",");
					var newPoint:PointGeometry=new PointGeometry(coord[0], coord[1], 0);
					var feature:Feature=new Feature();
					feature.geometry=newPoint;
					feature.geoStyle=pointstyle;
					//feature.objectId = -1;
					dynamicLayer.addFeature(feature);
					feature.executeDrawing();
					new GlowTween(feature, repeatCount, 0xFF0000, 1, 5, false, delay);

					/*var loc:Location = feature.getLocation();
					_map.center = (new Location(newPoint.x, newPoint.y));
					_map.moveTo(new Location(newPoint.x, newPoint.y), 14);*/
				}
			}
			catch (error:Error)
			{
				Alert.show("参数错误");
			}
		}


		/**
		 * 闪烁线
		 *
		 * @param polylineString 线字符串
		 * @param delay 闪烁间隔（毫秒）
		 * @param repeatCount 闪烁次数
		 * @param markerSymbolObject 脚本传入的线符号对象
		 */
		public function flashPolyline(polylineString:String, delay:Number, repeatCount:int, lineSymbolObject:Object):void
		{
			try
			{
				var dynamicLayer:FeatureLayer=_map.getLayerById(-101) as FeatureLayer;
				if (!dynamicLayer)
					dynamicLayer=new FeatureLayer(-101, "红线图层-线");


				dynamicLayer.layerType=LayerTypeEnum.DYNAMICLAYER;
				var linestyle:PolylineStyle=new PolylineStyle();
				linestyle.color=lineSymbolObject.color;
				linestyle.alpha=lineSymbolObject.alpha;
				linestyle.width=lineSymbolObject.width;
				if (lineSymbolObject.style)
				{
					if (lineSymbolObject.style != "solid")
						linestyle.dashMode=lineSymbolObject.style;
				}
				dynamicLayer.geoStyle=linestyle;
				_map.addLayer(dynamicLayer);
				var coords:Array=polylineString.split(",");
				var pointList:ArrayCollection=new ArrayCollection();
				for (var i:int=0; i < coords.length; i+=2)
				{
					pointList.addItem(new PointGeometry(coords[i], coords[i + 1], 0));
				}

				var newLine:PolylineGeometry=new PolylineGeometry();
				newLine.pointList=pointList;
				var feature:Feature=new Feature();
				feature.geometry=newLine;
				dynamicLayer.addFeature(feature);
				feature.executeDrawing();
				new GlowTween(feature, repeatCount, 0xFF0000, 1, 5, false, delay);


				_map.center=feature.getLocation();

			}
			catch (error:Error)
			{
				Alert.show("参数错误");
			}

		}

		/**
		 * 闪烁面
		 *
		 * @param polylineString 面字符串
		 * @param delay 闪烁间隔（毫秒）
		 * @param repeatCount 闪烁次数
		 * @param markerSymbolObject 脚本传入的填充符号对象
		 */
		public function flashPolygon(polygonString:String, delay:Number, repeatCount:int, fillSymbolObject:Object):void
		{
			try
			{
				var dynamicLayer:FeatureLayer=_map.getLayerById(-102) as FeatureLayer;
				if (!dynamicLayer)
					dynamicLayer=new FeatureLayer(-102, "红线图层-面");

				dynamicLayer.layerType=LayerTypeEnum.DYNAMICLAYER;
				var areastyle:PolygonStyle=new PolygonStyle();
				areastyle.fillColor=fillSymbolObject.fillColor;
				areastyle.fillAlpha=fillSymbolObject.fillAlpha;
				if (fillSymbolObject.edgeWidth)
					areastyle.edgeWidth=fillSymbolObject.edgeWidth;
				if (fillSymbolObject.edgeColor)
					areastyle.edgeColor=fillSymbolObject.edgeColor;
				if (fillSymbolObject.edgeAlpha)
					areastyle.edgeAlpha=fillSymbolObject.edgeAlpha;

				dynamicLayer.geoStyle=areastyle;
				_map.addLayer(dynamicLayer);
				var coords:Array=polygonString.split(",");
				var pointList:ArrayCollection=new ArrayCollection();
				for (var i:int=0; i < coords.length; i+=2)
				{
					pointList.addItem(new PointGeometry(coords[i], coords[i + 1], 0));
				}
				if ((coords[0] != coords[coords.length - 2]) || (coords[1] != coords[coords.length - 1]))
					pointList.addItem(new PointGeometry(coords[0], coords[1], 0));
				var newLine:PolylineGeometry=new PolylineGeometry();
				newLine.pointList=pointList;
				var newArea:PolygonGeometry=new PolygonGeometry();
				newArea.lineList=new ArrayCollection();
				newArea.lineList.addItem(newLine);
				var feature:Feature=new Feature();
				feature.geometry=newArea;
				dynamicLayer.addFeature(feature);
				feature.executeDrawing();
				new GlowTween(feature, repeatCount, 0xFF0000, 1, 5, false, delay);


				_map.center=feature.getLocation();

			}
			catch (error:Error)
			{
				Alert.show("参数错误");
			}
		}

		/**
		 * 鼠标滚轴事件
		 *
		 * @param param1 鼠标事件
		 */
		public function onMousewheelHandler(eventobj:Object):void
		{
			var event:MouseEvent=new MouseEvent(MouseEvent.MOUSE_WHEEL, true, false, eventobj.localX, eventobj.localY, null, false, false, false, false, eventobj.delta);
			_map.dispatchEvent(event);

		}
	}
}
